﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Emoney.UserTraining.Comm;
using Emoney.UserTraining.DAL;
using Emoney.UserTraining.Model;
using Emoney.UserTraining.Cache;

namespace Emoney.UserTraining.BLL
{
    public class Traning_NetworkMeetingBLL
    {
        private readonly Traning_NetworkMeetingDAL dal = new Traning_NetworkMeetingDAL();
        public List<Traning_NetworkMeeting> GetAllList()
        {
            List<Traning_NetworkMeeting> lst = new List<Traning_NetworkMeeting>();
            News2CacheTools cache = new News2CacheTools();
            string key = "lstrain_four";
            var obj = cache.Get<List<Traning_NetworkMeeting>>(key);
            if (obj != null)
            {
                lst = obj;
            }
            else
            {
                lst = dal.GetAllList().Where(x => x.allperson == "2" || x.end_date < DateTime.Now).OrderByDescending(x => x.class_date).ToList();
                cache.Add(key, lst, 0, 5, 0);
            }
            return lst;
        }
        public List<Traning_MeetingType> GetMeetingType()
        {
            List<Traning_MeetingType> lst = new List<Traning_MeetingType>();
            News2CacheTools cache = new News2CacheTools();
            string key = "lstrainGetMeetingType";
            var obj = cache.Get<List<Traning_MeetingType>>(key);
            if (obj != null)
            {
                lst = obj;
            }
            else
            {
                lst = dal.GetMeetingType();
                cache.Add(key, lst, 0, 5, 0);
            }
            return lst;
        }
        /// <summary>
        /// 所有未开始的会议或正在进行的课程
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public List<Traning_NetworkMeeting> GetNetAll()
        {
            Traning_NetworkMeetingDAL dal = new Traning_NetworkMeetingDAL();

            string key = "TrainingNetMeetingCache";
            News2CacheTools cache = new News2CacheTools();
            var obj = cache.Get<List<Traning_NetworkMeeting>>(key);
            List<Traning_NetworkMeeting> lstall = new List<Traning_NetworkMeeting>();
            //lstall = dal.GetAll();
            if (obj == null)
            {
                lstall = dal.GetAll();
                cache.Add(key, lstall, 0, 1, 0);
            }
            else
            {
                lstall = obj;
            }
            return lstall;
        }

        public List<Traning_NetworkMeeting> GetMonthLst(Traning_NetworkMeeting_Query query)
        {
            News2CacheTools cache = new News2CacheTools();
            string key = "monthAlltrain";
            var obj = cache.Get<List<Traning_NetworkMeeting>>(key);
            List<Traning_NetworkMeeting> list = new List<Traning_NetworkMeeting>();
            if (obj != null)
            {
                list = obj;
            }
            else
            {
                list = dal.GetMonthLst(query);
                cache.Add(key, list, 0, 1, 0);
            }
            return list;
        }
        /// <summary>
        /// 课程表的数据
        /// </summary>
        /// <returns></returns>
        public List<Traning_NetworkMeeting> GetCourse(Traning_NetworkMeeting_Query query)
        {
            return dal.GetCourse(query);
        }

        /// <summary>
        /// 查询历史数据
        /// </summary>
        /// <returns></returns>
        public List<Traning_NetworkMeeting> GetHistryList(Traning_NetworkMeeting_Query query)
        {
            return dal.GetHistryList(query);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<Traning_NetworkMeeting> GetList(Traning_NetworkMeeting_Query query)
        {
            List<Traning_NetworkMeeting> list = new List<Traning_NetworkMeeting>();
            list = dal.GetList(query);
            return list;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public List<Traning_NetworkMeeting> GetList(string mtg_id)
        {
            return dal.GetList(mtg_id);
        }

        /// <summary>
        /// 查询多次会议未开始的会议
        /// </summary>
        /// <param name="click_num"></param>
        /// <returns></returns>
        public List<Traning_NetworkMeeting> GetListBy(string click_num)
        {
            return dal.GetListBy(click_num);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Traning_NetworkMeeting GetModel(int id)
        {
            return dal.GetModel(id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public int ModifyNetworkMeeting(Traning_NetworkMeeting c)
        {
            int rows = 0;
            if (c.click_num != "0" && c.Id != 0)
            {
                rows += dal.AddUpdate(c);
                List<Traning_NetworkMeeting> list = GetListBy(c.click_num);
                foreach (Traning_NetworkMeeting model in list)
                {
                    if (model.Id == c.Id)
                    {
                        continue;
                    }
                    c.Id = model.Id;
                    c.class_date = c.class_date.AddDays(1);
                    rows += dal.AddUpdate(c);
                }
            }
            else
            {
                rows = dal.AddUpdate(c);
            }
            return rows;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int deleteNetworkMeeting(string id)
        {
            return dal.Delete(id);
        }

        /// <summary>
        /// 结束会议
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int deleteAllperson(int id)
        {
            return dal.deleteAllperson(id);
        }

        /// <summary>
        /// 会议推荐和取消推荐
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isRecommend"></param>
        /// <returns></returns>
        public int Recommend(int id, string isRecommend)
        {
            return dal.Recommend(id, isRecommend);
        }

        /// <summary>
        /// 视频推荐和取消推荐
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isRecommend"></param>
        /// <returns></returns>
        public int VideoRecommend(int id, string isRecommend)
        {
            return dal.VideoRecommend(id, isRecommend);
        }

        /// <summary>
        /// 视频维护
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateNetworkMeeting(Traning_NetworkMeeting model)
        {
            return dal.UpdateNetworkMeeting(model);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="checknum"></param>
        /// <returns></returns>
        public int deletetochecknum(string checknum,string updatetype)
        {
            if (checknum != "0" && checknum != "1")
            {
                return dal.deletetochecknum(checknum,updatetype);
            }
            return 1;
        }


        public string CreateMeeting(Traning_NetworkMeeting net)
        {
            string StrKey = "2012110812345678";

            string siteid = "emoney";
            string flag = "2";
            string title = StrToHex(net.mtg_name);
            string mtgkey = "100000" + net.Id;
            string mtgpwd = EncryptUtil.EncryptAES(net.mtg_password, StrKey);
            string hostpwd = EncryptUtil.EncryptAES(net.host_key, StrKey);
            string duration = ((Convert.ToInt32(net.Duration_date) + Convert.ToInt32(net.before_time)) * 60).ToString();
            string username = StrToHex("luobin");
            string usertype = "3";
            string language = "0";
            string UserID = "admin";
            string timestamp = net.isCreateMeeting;

            //timestamp = "2012-11-08 18:00:00";

            string str = "http://emoney.cenwave.com/join_mtg_sp1.asp?";
            str += "SiteID=" + siteid;   //站点标识
            str += "&ProductFlag=" + flag;  //1: 课堂2: 会议
            str += "&MtgTitle=" + title;  //会议标题
            str += "&MtgKey=" + mtgkey;
            str += "&MtgPwd=" + mtgpwd;
            str += "&HostPwd=" + hostpwd;
            str += "&Duration=" + duration;
            str += "&UserName=" + username;
            str += "&UserID=" + UserID;
            str += "&UserType=" + usertype;
            str += "&language=" + language;
            str += "&Timestamp=" + timestamp;
            str += "&authid=" + EncryptUtil.MD5(StrKey + siteid + mtgkey + language + usertype + timestamp, 32);

            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mtg_name"></param>
        /// <returns></returns>
        public string OneMeetingID(string mtg_name)
        {
            string str = returnRUL();
            string mtg_id = "";
            for (int i = 0; i < str.Split('@').Length; i++)
            {
                string aa = str.Split('@')[i];
                if (str.Split('@')[i].Contains(mtg_name))
                {
                    mtg_id = str.Split('@')[i + 1];
                    mtg_id = mtg_id.Substring(3);
                    break;
                }
            }
            return mtg_id;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string StrToHex(string str)
        {
            byte[] data = System.Text.Encoding.GetEncoding("utf-8").GetBytes(str);
            StringBuilder sb = new StringBuilder();
            foreach (var c in data)
            {
                sb.AppendFormat("%{0:x2}", c);
            }
            return sb.ToString();
        }

        public string sessionkey = "";
        public string sessionId = "";
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string returnRUL()
        {
            string str = "";
            int count = 0;
            string url = "http://emoney.cenwave.com/main/join.asp?site_id=1062&language=Chinese&service_type=0&tel=&random=" + System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string tz = StrToHex("GMT 0800");
            string hexurl = "http://emoney.cenwave.com/getClientTimeZone.asp?tz=" + tz + "&url=" + StrToHex(url);

            //hexurl = "";

            while (string.IsNullOrEmpty(sessionId))
            {
                str = LoadData(hexurl); ;
                count++;
                if (count > 5)
                {
                    break;
                }
            }
            if (!string.IsNullOrEmpty(sessionId))
            {
                str = LoadData(hexurl);
            }
            string[] sArray = Regex.Split(str, "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">", RegexOptions.IgnoreCase);
            if (sArray.Length > 2)
            {
                str = sArray[2];
                str = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">" + str.Substring(0, str.Length - 75);
                str = NoHTML(str);
            }
            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string LoadData(string url)
        {
            string rel = "";
            try
            {
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
                hwr.Method = "GET";
                hwr.KeepAlive = true;
                hwr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                hwr.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
                hwr.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1";
                hwr.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
                //hwr.Host = "emoney.cenwave.com";
                if (sessionId != "")
                {
                    //hwr.Headers.Add("Cookie", "ASPSESSIONIDQQDSAQCB=HBIKFNKAMCNEOJGMNKBKDHFO");
                    hwr.Headers.Add("Cookie", sessionkey + "=" + sessionId);
                }
                //hwr.Referer = "";
                hwr.ServicePoint.Expect100Continue = true;
                hwr.Referer = url;
                HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
                System.IO.Stream myResponseStreame = response.GetResponseStream();
                System.IO.StreamReader sdr = new System.IO.StreamReader(myResponseStreame, Encoding.GetEncoding("utf-8"));
                rel = sdr.ReadToEnd().ToString();
                var strCookie = response.Headers["Set-Cookie"];
                GetCookieValue(strCookie);
            }
            catch (Exception ex)
            {
                sessionkey = "";
                sessionId = "";
            }
            return rel;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strCookie"></param>
        /// <returns></returns>
        public string GetCookieValue(string strCookie)
        {
            if (string.IsNullOrEmpty(strCookie))
            {
                return string.Empty;
            }
            strCookie = strCookie.Replace("; path=/", "");
            var lst = strCookie.Split(';');
            foreach (var c in lst)
            {
                var tkey = c.Split('=');
                if (tkey.Length > 0)
                {
                    sessionkey = tkey[0];
                    sessionId = tkey[1];
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Htmlstring"></param>
        /// <returns></returns>
        public string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
              RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "@",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "",
              RegexOptions.IgnoreCase);

            Htmlstring = Htmlstring.Replace("<", "");
            Htmlstring = Htmlstring.Replace(">", "");
            Htmlstring = Htmlstring.Replace("\r\n", "");
            Htmlstring = Htmlstring.Replace(" ", "");
            Htmlstring = Htmlstring.Substring(1, Htmlstring.Length - 2);
            return Htmlstring;
        }

        public string ThreadAllMtg()
        {
            string mtgError = GetCenwave();
            return mtgError;
        }

        /// <summary>
        /// 自动程序
        /// </summary>
        /// <returns></returns>
        public string ThreadFunMtgID()
        {
            string mtgError = GetCenwave();
            string str = "";
            if (mtgError != "@@")
            {

                string yid = mtgError.Split('@')[0];
                string nid = mtgError.Split('@')[1];
                string cid = mtgError.Split('@')[2];

                if (yid != "")
                {
                    str += "在盛维网络平台中：标题为(" + yid + ")所对应的会议标题,未找到相应的数据。";
                }

                if (nid != "")
                {
                    str += "在盛维网络平台中：标题为(" + nid + ")所对应的会议标题跟盛维平台数据不对应。";
                }

                if (cid != "")
                {
                    str += "在盛维网络平台中：标题为(" + cid + ")离开始时间还有一个小时仍然未获取到会议编号。";
                }
            }
            return str;
        }

        public string GetCenwave()
        {
            string mtgError = "";
            string nid = ""; //会议ID取错了
            string yid = ""; //没有在盛维网络会议中找到该数据
            string cid = ""; //会议开始前一个小时内没有取到会议编号
            List<Traning_NetworkMeeting> list = dal.GetAll();

            string str = returnRUL();

            if (list.Count > 0 && str != "")
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].mtg_id != "")
                    {
                        string mtg_id = "";

                        for (int j = 0; j < str.Split('@').Length; j++)
                        {
                            string aa = str.Split('@')[j];
                            string mtg_name = list[i].mtg_name.Length > 11 ? list[i].mtg_name.Substring(0, 11) : list[i].mtg_name;
                            mtg_name = mtg_name.Replace("（", "(");
                            if (mtg_name.Contains("("))
                            {
                                mtg_name = mtg_name.Split('(')[0].ToString();
                            }
                            if (str.Split('@')[j].Contains(mtg_name))
                            {
                                if (Convert.ToDateTime(list[i].class_date).ToString("yyyy-MM-ddHH:mm:sss") == str.Split('@')[j + 2])
                                {
                                    mtg_id = str.Split('@')[j + 1];
                                    mtg_id = mtg_id.Substring(3);
                                    if (list[i].mtg_id != mtg_id)
                                    {
                                        nid += list[i].mtg_name.ToString() + "^";
                                    }
                                    break;
                                }
                            }
                        }

                        if (Convert.ToDateTime(list[i].class_date).ToString("yyyy-MM-dd") == System.DateTime.Now.ToString("yyyy-MM-dd"))
                        {
                            if (mtg_id == "")
                            {
                                yid += list[i].mtg_name.ToString() + "^";
                            }
                        }
                    }
                    else
                    {
                        for (int j = 0; j < str.Split('@').Length; j++)
                        {
                            string aa = str.Split('@')[j];
                            string mtg_name = list[i].mtg_name.Length > 11 ? list[i].mtg_name.Substring(0, 11) : list[i].mtg_name;
                            if (str.Split('@')[j].Contains(mtg_name))
                            {
                                if (Convert.ToDateTime(list[i].class_date).ToString("yyyy-MM-ddHH:mm:sss") == str.Split('@')[j + 2])
                                {
                                    string mtg_id = str.Split('@')[j + 1];
                                    mtg_id = mtg_id.Substring(3);

                                    dal.Modifymtg_id(list[i].Id, mtg_id);
                                    break;
                                }
                            }
                        }

                    }
                }

            }

            if (yid != "")
            {
                yid = yid.Substring(0, yid.Length - 1);
            }

            if (nid != "")
            {
                nid = nid.Substring(0, nid.Length - 1);
            }

            List<Traning_NetworkMeeting> listtime = dal.GetAll();
            if (listtime != null && listtime.Count > 0)
            {
                listtime = listtime.Where(x => x.mtg_id == "").ToList();
                for (int i = 0; i < listtime.Count; i++)
                {
                    if (Convert.ToDateTime(listtime[i].class_date).AddHours(-1) < System.DateTime.Now)
                    {
                        cid += list[i].mtg_name.ToString() + "^";
                    }
                }
            }

            if (cid != "")
            {
                cid = cid.Substring(0, cid.Length - 1);
            }

            mtgError = yid + "@" + nid + "@" + cid;

            return mtgError;
        }
        public List<Traning_NetworkMeeting> GetMeetByType(string meetType)
        {
            return dal.GetMeetByType(meetType).ToList();
        }


        public void addNetWorkMeetingCache(int number)
        {
            string key = "NetMeetingCacheNumber";
            News2CacheTools cache = new News2CacheTools();
            if (number < 1500)
            {

                cache.Add(key, number.ToString(), 0, 0, 300);
            }
            else if (number > 1800)
            {
                cache.Add(key, number.ToString(), 0, 0, 5);
            }
            else
            {
                cache.Add(key, number.ToString(), 0, 0, 30);
            }
        }

        public int getNetWorkMeetingCache()
        {
            string key = "NetMeetingCacheNumber";
            News2CacheTools cache = new News2CacheTools();
            string aa = cache.Get<string>(key);
            if (aa == "")
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(aa);
            }
        }
    }
}
